package com.hskn.hss.utils;

import com.hskn.hss.utils.redis.RedisUtil;
import com.hskn.hss.utils.redis.key.LoginUidAndTicketKey;
import com.hskn.hss.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class WebSocketUtils {

    /**
     * 发送消息到某个人
     *
     * @param message
     * @param toUserId
     */
    public static void sendMessageToOne(String message, String toUserId) {
        try {
            List<String> tickets = RedisUtil.getAllList(LoginUidAndTicketKey.token, toUserId, String.class);
            if (!CollectionUtils.isEmpty(tickets)) {
                for (String ticket : tickets) {
                    log.info("==发送websocket，ticket:{},message:{}", ticket, message);
                    WebSocketServer.sendInfo(message, ticket);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            log.error("sendMessageToOne发送消息失败，", e);
        }
    }

    /**
     * 发送消息到所有人
     *
     * @param message
     */
    public static void sendMessageToAll(String message) {
        try {
            ConcurrentHashMap<String, WebSocketServer> map = WebSocketServer.getWebSocketMap();
            if (CollectionUtils.isEmpty(map)) {
                log.info("--sendMessageToAll，无连接");
                return;
            }
            for (Map.Entry<String, WebSocketServer> entry : map.entrySet()) {
                String userId = entry.getKey();
                WebSocketServer socketServer = entry.getValue();
                socketServer.sendInfo(message, userId);
            }
        } catch (IOException e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);
        }
    }
}
